package com.jiazhong.boot.upload.controller;

import com.jiazhong.boot.commons.util.JsonResult;
import com.jiazhong.boot.commons.util.ResultTool;
import lombok.SneakyThrows;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @SneakyThrows
    @PostMapping
    public JsonResult upload(@RequestParam("file") MultipartFile file) {
        // 上传的位置
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "/static/images";
        // 上传后的文件名
        // 1.png
        String originalFilename = file.getOriginalFilename();
        // .png
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + type;
        File src = new File(filePath, fileName);
        file.transferTo(src);
        return ResultTool.success("success");
    }
}
